<?php
// Register Custom Post Type for Sliders 
//sahifa 主题的幻灯片脚本的进阶版本
function tie_slider_register() {
    $labels = array(
        'name' => __('Custom Sliders', 'tie'),
        'singular_name' => __('Slider', 'tie'),
        'add_new_item' => __('Add New Slider', 'tie'),
        'menu_name'  => __( '幻灯片', 'tie' )
    );

    $args = array(
        'labels' => $labels,
        'public' => false,
        'show_ui' => true,
        'menu_icon' => '',
        'exclude_from_search' => true,
        'hierarchical' => false,
        'menu_position' => 6,
        'supports' => array('title','thumbnail','custom-fields'),
    );

    register_post_type('tie_slider', $args);
}
add_action('init', 'tie_slider_register');

// Add Meta Box for Slider Items
function tie_slider_init() {
    add_meta_box("tie_slider_slides", "Slides", "tie_slider_slides", "tie_slider", "normal", "high");
}
add_action("admin_init", "tie_slider_init");

// Display Slider Items Meta Box
function tie_slider_slides() {
    global $post;
    $slider = get_post_meta($post->ID, 'custom_slider', true);
    wp_nonce_field(basename(__FILE__), 'custom_slider_nonce');
    ?>
    <div class="tie-slider-wrapper">
        <div class="tie-slider-header">
            <h2><?php _e('Slider Management', 'tie'); ?></h2>
            <button id="upload_add_slide" type="button" class="button button-primary">
                <span class="dashicons dashicons-plus-alt2"></span>
                <?php _e('Add New Slide', 'tie') ?>
            </button>
        </div>
        <ul id="tie-slider-items">
            <?php
            if (!empty($slider)) {
                foreach ($slider as $i => $slide) { 
                    $slide_image = wp_get_attachment_image_url( $slide['id'], 'thumbnail' );
                    
                    ?>
                    <li id="listItem_<?php echo $i ?>" class="tie-slide-item">
                        <div class="tie-slide-content">
                            <div class="tie-slide-image">
                                <div class="image-wrapper">
                                    <img src="<?php echo esc_url($slide_image); ?>" alt="" <?php echo strpos($slide_image, '.svg') !== false ? 'style="width:100px; height:auto;"' : ''; ?> />
                                    <?php //echo wp_get_attachment_image($slide['id'], 'medium'); ?>
                                    <button class="change-image button" data-index="<?php echo $i ?>">
                                        <span class="dashicons dashicons-edit"></span> Change Image
                                    </button>
                                </div>
                            </div>
                            <div class="tie-slide-details">
                                <label>
                                    <span><?php _e('Slide Title:', 'tie') ?></span>
                                    <input name="custom_slider[<?php echo $i ?>][title]" value="<?php echo esc_attr($slide['title']) ?>" type="text" />
                                </label>
                                <label>
                                    <span><?php _e('Slide Link:', 'tie') ?></span>
                                    <input name="custom_slider[<?php echo $i ?>][link]" value="<?php echo esc_attr($slide['link']) ?>" type="text" />
                                </label>
                                <label>
                                    <span><?php _e('Slide Caption:', 'tie') ?></span>
                                    <textarea name="custom_slider[<?php echo $i ?>][caption]"><?php echo esc_textarea($slide['caption']) ?></textarea>
                                </label>
                                <input name="custom_slider[<?php echo $i ?>][id]" value="<?php echo esc_attr($slide['id']) ?>" type="hidden" class="slide-image-id" />
                            </div>
                        </div>
                        <div class="tie-slide-actions">
                            <a class="button tie-move-slide"><span class="dashicons dashicons-move"></span></a>
                            <a class="button tie-delete-slide"><span class="dashicons dashicons-trash"></span></a>
                        </div>
                    </li>
                    <?php
                }
            }
            ?>
        </ul>
    </div>

    <style>
        .tie-slider-wrapper {
            background: #fff;
            border: 1px solid #e5e5e5;
            box-shadow: 0 1px 1px rgba(0,0,0,.04);
            margin-top: 20px;
        }
        .tie-slider-header {
            background: #f5f5f5;
            border-bottom: 1px solid #e5e5e5;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .tie-slider-header h2 {
            margin: 0;
        }
        #tie-slider-items {
            padding: 20px;
        }
        .tie-slide-item {
            background: #f9f9f9;
            border: 1px solid #e5e5e5;
            margin-bottom: 10px;
            padding: 15px;
            display: flex;
            align-items: flex-start;
        }
        .tie-slide-content {
            flex-grow: 1;
            display: flex;
        }
        .tie-slide-image {
            margin-right: 20px;
            width: 150px;
        }
        .tie-slide-image img {
            max-width: 100%;
            height: auto;
            margin-bottom: 10px;
        }
        .image-wrapper {
            position: relative;
        }
        .change-image {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            opacity: 0;
            transition: opacity 0.3s;
        }
        .image-wrapper:hover .change-image {
            opacity: 1;
        }
        .tie-slide-details {
            flex-grow: 1;
        }
        .tie-slide-details label {
            display: block;
            margin-bottom: 10px;
        }
        .tie-slide-details span {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .tie-slide-details input[type="text"],
        .tie-slide-details textarea {
            width: 100%;
        }
        .tie-slide-actions {
            margin-left: 10px;
        }
        .tie-slide-actions button {
            display: block;
            margin-bottom: 5px;
        }
    </style>

    <script>
    jQuery(document).ready(function($) {
        $("#tie-slider-items").sortable({
            opacity:0.6,
            revert:true,
            handle: '.tie-move-slide',
            update: function(event, ui) {
                console.log('success drag');
                updateSlideOrder();
            }
        });

       

        var tie_uploader;
        var nextCell = $('#tie-slider-items li').length;

        $('#upload_add_slide').on('click', function(event) {
            event.preventDefault();
            openMediaUploader(function(selection) {
                selection.each(function(attachment) {
                    attachment = attachment.toJSON();
                    $('#tie-slider-items').append(
                        '<li id="listItem_' + nextCell + '" class="tie-slide-item">' +
                        '<div class="tie-slide-content">' +
                        '<div class="tie-slide-image">' +
                        '<div class="image-wrapper">' +
                        '<img src="' + attachment.url + '" alt="">' +
                        '<button class="change-image button" data-index="' + nextCell + '">' +
                        '<span class="dashicons dashicons-edit"></span> Change Image' +
                        '</button>' +
                        '</div>' +
                        '</div>' +
                        '<div class="tie-slide-details">' +
                        '<label><span><?php _e('Slide Title:', 'tie') ?></span><input name="custom_slider[' + nextCell + '][title]" value="" type="text" /></label>' +
                        '<label><span><?php _e('Slide Link:', 'tie') ?></span><input name="custom_slider[' + nextCell + '][link]" value="" type="text" /></label>' +
                        '<label><span><?php _e('Slide Caption:', 'tie') ?></span><textarea name="custom_slider[' + nextCell + '][caption]"></textarea></label>' +
                        '<input name="custom_slider[' + nextCell + '][id]" value="' + attachment.id + '" type="hidden" class="slide-image-id" />' +
                        '</div></div>' +
                        '<div class="tie-slide-actions">' +
                        '<button class="button tie-move-slide"><span class="dashicons dashicons-move"></span></button>' +
                        '<button class="button tie-delete-slide"><span class="dashicons dashicons-trash"></span></button>' +
                        '</div></li>'
                    );
                    nextCell++;
                    updateSlideOrder();
                });
            });
        });

        $(document).on('click', '.tie-delete-slide', function(event) {
            event.preventDefault();
            $(this).closest('.tie-slide-item').remove();
            updateSlideOrder();
        });

        $(document).on('click', '.change-image', function(event) {
            event.preventDefault();
            var $button = $(this);
            var slideIndex = $button.data('index');
            openMediaUploader(function(selection) {
                selection.each(function(attachment) {
                    attachment = attachment.toJSON();
                    var $slide = $button.closest('.tie-slide-item');
                    $image = $slide.find('img');
                    console.log($image);
                    $slide.find('img').attr('src', attachment.url);
                    $slide.find('.slide-image-id').val(attachment.id);
                    
                });
            });
        });

        function openMediaUploader(callback) {
            tie_uploader = wp.media.frames.tie_uploader = wp.media({
                title: '<?php _e('Select Image', 'tie') ?>',
                library: { type: 'image' },
                button: { text: 'Select' },
                multiple: false
            });

            tie_uploader.on('select', function() {
                var selection = tie_uploader.state().get('selection');
                callback(selection);
            });

            tie_uploader.open();
        }

        function updateSlideOrder() {
            $('#tie-slider-items li').each(function(index) {
                
                $(this).find('input, textarea, .change-image').each(function() {
                    var oldName = $(this).attr('name');
                    if (oldName) {
                        var newName = oldName.replace(/\[\d+\]/, '[' + index + ']');
                        $(this).attr('name', newName);
                    }
                    if ($(this).hasClass('change-image')) {
                        $(this).data('index', index);
                    }
                });

            });
        }

        $('form#post').on('submit', function(e) {
            updateSlideOrder();
        });
    });
    </script>
    <?php
}

// Save Slider Data
function tie_save_slide($post_id) {
    if (!isset($_POST['custom_slider_nonce']) || !wp_verify_nonce($_POST['custom_slider_nonce'], basename(__FILE__))) {
        return $post_id;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    if ('tie_slider' != $_POST['post_type']) {
        return $post_id;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }

    if (!empty($_POST['custom_slider'])) {
        $sanitized_slider = array();
        foreach ($_POST['custom_slider'] as $key => $slide) {
            $sanitized_slider[$key] = array(
                'title' => sanitize_text_field($slide['title']),
                'link' => esc_url_raw($slide['link']),
                'caption' => wp_kses_post($slide['caption']),
                'id' => absint($slide['id'])
            );
        }
        update_post_meta($post_id, 'custom_slider', $sanitized_slider);
    } else {
        delete_post_meta($post_id, 'custom_slider');
    }
}
add_action('save_post', 'tie_save_slide');

// Enqueue necessary scripts and styles
function tie_admin_enqueue_scripts($hook) {
   global $post;

    if ('post.php' == $hook || 'post-new.php' == $hook) {
        if ('tie_slider' == $post->post_type) {
            wp_enqueue_media();
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_style('dashicons');
        }
    }
}
add_action('admin_enqueue_scripts', 'tie_admin_enqueue_scripts');


function fetch_slider_images($slider_id) {
    

    
    $slider_data = get_post_meta($slider_id, 'custom_slider', true);
    $images = array();

    if (!empty($slider_data) && is_array($slider_data)) {
        foreach ($slider_data as $slide) {
            if (!empty($slide['id'])) {
                $image_url = wp_get_attachment_image_url($slide['id'], 'full');
                if ($image_url) {
                    $images[] = array(
                        'url' => $image_url,
                        'title' => isset($slide['title']) ? $slide['title'] : '',
                        'caption' => isset($slide['caption']) ? $slide['caption'] : '',
                        'link' => isset($slide['link']) ? $slide['link'] : ''
                    );
                }
            }
        }
    }

    return $images;
}
?>
